import { Logger as TypeOrmLogger, QueryRunner } from 'typeorm';
import { Logger } from '@nestjs/common';

/**
 * 自定义TypeORM日志记录器
 * 用于记录数据库查询和错误
 */
export class TypeormLogger implements TypeOrmLogger {
  private readonly logger = new Logger('SQL');

  /**
   * 记录查询
   */
  logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner): void {
    if (queryRunner?.data?.isTransactionActive) {
      this.logger.debug(
        `Transaction(${queryRunner.data.transactionId}) Query: ${query} -- Parameters: ${this.stringifyParameters(
          parameters,
        )}`,
      );
    } else {
      this.logger.debug(
        `Query: ${query} -- Parameters: ${this.stringifyParameters(parameters)}`,
      );
    }
  }

  /**
   * 记录查询错误
   */
  logQueryError(
    error: string | Error,
    query: string,
    parameters?: any[],
    queryRunner?: QueryRunner,
  ): void {
    if (queryRunner?.data?.isTransactionActive) {
      this.logger.error(
        `Transaction(${queryRunner.data.transactionId}) Query Error: ${query} -- Parameters: ${this.stringifyParameters(
          parameters,
        )} -- Error: ${error}`,
      );
    } else {
      this.logger.error(
        `Query Error: ${query} -- Parameters: ${this.stringifyParameters(
          parameters,
        )} -- Error: ${error}`,
      );
    }
  }

  /**
   * 记录查询慢
   */
  logQuerySlow(
    time: number,
    query: string,
    parameters?: any[],
    queryRunner?: QueryRunner,
  ): void {
    if (queryRunner?.data?.isTransactionActive) {
      this.logger.warn(
        `Transaction(${queryRunner.data.transactionId}) Slow Query (${time}ms): ${query} -- Parameters: ${this.stringifyParameters(
          parameters,
        )}`,
      );
    } else {
      this.logger.warn(
        `Slow Query (${time}ms): ${query} -- Parameters: ${this.stringifyParameters(
          parameters,
        )}`,
      );
    }
  }

  /**
   * 记录架构构建开始
   */
  logSchemaBuild(message: string): void {
    this.logger.log(`Schema Build: ${message}`);
  }

  /**
   * 记录迁移开始
   */
  logMigration(message: string): void {
    this.logger.log(`Migration: ${message}`);
  }

  /**
   * 记录一般信息
   */
  log(level: 'log' | 'info' | 'warn', message: any): void {
    switch (level) {
      case 'log':
      case 'info':
        this.logger.log(message);
        break;
      case 'warn':
        this.logger.warn(message);
        break;
    }
  }

  /**
   * 将参数转换为字符串
   */
  private stringifyParameters(parameters?: any[]): string {
    if (!parameters || !parameters.length) {
      return 'No parameters';
    }

    try {
      return JSON.stringify(parameters);
    } catch (error) {
      console.log(error);
      return `${parameters.join('')}`;
    }
  }
}
